<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 提示区域 -->
      <el-alert title="填写商品的信息" type="info" center show-icon></el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        align-center
        process-status="finish"
        :active="TabStepActive - 0"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="提交请求"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <div v-show="tabDiv">
        <el-tabs
          type="border-card"
          v-model="TabStepActive"
          tab-position="left"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form
              :model="addGoodsForm"
              :rules="addGoodsBaseFormRules"
              ref="addGoodsBaseFormRef"
              label-width="100px"
            >
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="addGoodsForm.name"></el-input>
              </el-form-item>
              <el-form-item label="副标题" prop="subtitle">
                <el-input v-model="addGoodsForm.subtitle"></el-input>
              </el-form-item>
              <el-form-item label="上线/下架" prop="status">
                <el-radio-group v-model="addGoodsForm.status">
                  <el-radio :label="1">
                    <el-tag type="success">上线</el-tag>
                  </el-radio>
                  <el-radio :label="0">
                    <el-tag type="danger">下架</el-tag>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="所属分类" prop="categoryId">
                <el-cascader
                  placeholder="选择商品所属分类"
                  :options="categoryList"
                  :props="categoryProp"
                  v-model="selectKeys"
                  @change="handleChange"
                  filterable
                ></el-cascader>
              </el-form-item>
              <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="addGoodsForm.price" :min="0"></el-input-number>
              </el-form-item>
              <el-form-item label="商品库存" prop="stock">
                <el-input-number v-model="addGoodsForm.stock" :min="0"></el-input-number>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="1">
            <el-upload
              :headers="uploadHeaders"
              action="http://localhost:8088/manage/product/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :on-change="fileChange"
              :on-exceed="fileExceed"
              :auto-upload="false"
              accept="image/*"
              drag
              multiple
              list-type="picture"
              ref="uploadRef"
              :limit="4"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击选取</em>
                图片
              </div>
              <div class="el-upload__tip" slot="tip">
                1.
                <strong>第一张图作为封面图!</strong>
                <br />2.只能上传image文件，且不超过1024kb，最多四张！
                <el-button
                  style="margin-left:80px;"
                  size="small"
                  @click="submitUpload"
                  type="primary"
                >上传到服务器</el-button>
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="2">
            <el-upload
              class="quill-upload"
              action="http://localhost:8088/product/upload"
              :headers="uploadHeaders"
              :on-success="quillUploadSuccess"
              :on-error="quillUploadError"
              :before-upload="quillBeforeUpload"
              :show-file-list="false"
              ref="quillUpload"
              accept="image/*"
              multiple
            ></el-upload>
            <quill-editor
              v-model="addGoodsForm.detail"
              ref="quillEditorRef"
              :options="editorOption"
              @change="onQuillChange($event)"
              @ready="onQuillReady($event)"
            ></quill-editor>
            <el-button style="margin-top:20px;" type="primary" @click="submitAdd">提交-添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-show="requestDiv" style="text-align:center;margin-top:50px;">
        <i class="el-icon-loading" style="font-size:100px;color:green;"></i>
        <p>提交请求中...</p>
      </div>
      <div v-show="successDiv" style="text-align:center;margin-top:50px;">
        <i class="el-icon-check" style="font-size:100px;color:green;"></i>
        <p>添加成功！</p>
        <el-button type="primary" @click="continueAdd">继续添加</el-button>
        <el-button type="warning" @click="backhome">返回</el-button>
      </div>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
      @close="previewDialogClosed"
      center
    >
      <img :src="previewInfo" :alt="previewInfo" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
// 富文本编辑器工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote', 'code-block'],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
  [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
  [{ direction: 'rtl' }], // text direction

  [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ['link', 'image', 'video'],
  ['clean'] // remove formatting button
]
export default {
  data() {
    return {
      TabStepActive: '0',
      addGoodsForm: {
        name: '',
        subtitle: '',
        status: 1,
        categoryId: 0,
        price: 0,
        stock: 0,
        subImages: [],
        detail: ''
      },
      addGoodsBaseFormRules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        subtitle: [
          {
            required: true,
            message: '请输入商品副标题',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '需要选择商品状态',
            trigger: 'blur'
          }
        ],
        categoryId: [
          {
            required: true,
            message: '请选择所属分类',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        stock: [
          {
            required: true,
            message: '请输入商品库存量',
            trigger: 'blur'
          }
        ]
      },
      //
      categoryList: [],
      //
      categoryProp: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true
      },
      //
      selectKeys: [],
      // 为上传文件添加请求头
      uploadHeaders: {
        Authorization: sessionStorage.getItem('CURRENT_TOKEN')
      },
      // 预览图片的信息存储
      previewInfo: '',
      //
      previewDialogVisible: false,
      // 富文本编辑器配置
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.quill-upload input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      //
      tabDiv: true,
      //
      requestDiv: false,
      //
      successDiv: false
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList() {
      const { data: res } = await this.$axios.get('manage/category/get_category_all')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.categoryList = res.data
    },
    //
    handleChange() {
      this.addGoodsForm.categoryId = this.selectKeys[this.selectKeys.length - 1]
    },
    //
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0') {
        let flag = false
        this.$refs.addGoodsBaseFormRef.validate(valid => {
          if (!valid) this.$message.warning('请先完成“基本信息”的填写')
          flag = valid
        })
        if (!flag) return flag
      }
      if (oldActiveName === '1' && activeName !== '0') {
        this.submitUpload()
      }
    },
    // 单击图片触发预览效果
    handlePreview(file) {
      this.previewInfo = file.url
      this.previewDialogVisible = true
    },
    // 移除图片 file是被删除的文件信息，filelist是剩下的文件信息
    handleRemove(file, filelist) {
      if (file.status === 'success') {
        const i = this.addGoodsForm.subImages.findIndex(value => value === file.response.data[0].uri)
        this.addGoodsForm.subImages.splice(i, 1)
      }
    },
    // 上传文件成功时触发
    uploadSuccess(response, file, filelist) {
      if (response.status !== 0) {
        file.status = 'ready'
        return this.$message.error('文件上传错误："' + response.msg + '"')
      }
      this.$message.success('文件上传完成！')
      response.data.forEach(value => {
        this.addGoodsForm.subImages.push(value.uri)
      })
    },
    // 上传文件失败时触发
    uploadError(erro, file, filelist) {
      file.status = 'ready'
      filelist.push(file)
      this.$message.error('文件上传中出现未知错误！请稍后再试~')
    },
    //
    fileChange(file, filelist) {
      // 限制图片格式
      if (file.raw.type.split('/')[0] !== 'image') {
        filelist.pop()
        return this.$message.warning('只能上传image格式文件')
      }
      // 限制图片大小
      if (file.size > 500 * 1024) {
        const i = filelist.findIndex(value => {
          return value.name === file.name
        })
        filelist.splice(i, 1)
        return this.$message.info('图片限制大小500KB')
      }
      // 限制重复图片
      let count = 0
      filelist.forEach(value => {
        if (file.name === value.name) count++
      })
      if (count > 1) {
        filelist.pop()
        return this.$message.info('该图片已存在')
      }
    },
    // 超出数量时触发
    fileExceed(file, filelist) {
      this.$message.warning('只能容纳最多四张图片！本次请求了 ' + file.length + ' 张，超出了限制！')
    },
    // 提交上传图片到服务器的请求
    submitUpload() {
      this.$refs.uploadRef.submit()
    },
    //
    previewDialogClosed() {
      this.previewInfo = ''
      this.previewDialogVisible = false
    },
    //
    submitAdd() {
      this.$refs.addGoodsBaseFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请检查下必填项是否全部填写！')
        this.$refs.uploadRef.submit()
        this.TabStepActive = '3'
        this.tabDiv = false
        this.requestDiv = true
        this.successDiv = false
        const dd = { ...this.addGoodsForm }
        dd.subImages = dd.subImages.join(',')
        const { data: res } = await this.$axios.post('manage/product/insert_goods', dd)
        if (res.status !== 0) {
          this.TabStepActive = '2'
          this.tabDiv = true
          this.requestDiv = false
          this.successDiv = false
          this.$message.error(res.msg)
          return
        }
        this.TabStepActive = '4'
        this.tabDiv = false
        this.requestDiv = false
        this.successDiv = true
        this.$message.success(res.msg)
      })
    },
    // 为富文本编辑器上传图片，上传成功
    quillUploadSuccess(response, file, list) {
      // file包含原文件信息以及服务器返回的数据
      // 获取富文本组件实例
      const quill = this.$refs.quillEditorRef.quill
      // 如果上传时出现错误
      if (response.status !== 0) return this.$message.error(response.msg)
      // 上传成功
      // 1.获取富文本中光标所在位置
      const index = quill.getSelection().index
      // 2.插入图片
      quill.insertEmbed(index, 'image', response.data[0].url)
      // 3.调整光标位置
      quill.setSelection(index + 1)
    },
    // 为富文本编辑器上传图片，上传发生错误
    quillUploadError() {
      this.$message.error('图片插入失败')
    },
    // 为富文本编辑器上传图片，上传之前
    quillBeforeUpload() {},
    // 富文本编辑器内容发生改变时立刻触发
    onQuillChange(value) {
      console.log('onQuillChange')
      this.addGoodsForm.detail = value.html
    },
    // 富文本编辑器准备好时触发
    onQuillReady(value) {
      console.log('onQuillReady')
    },
    //
    continueAdd() {
      // 清空
      this.addGoodsForm = {
        name: '',
        subtitle: '',
        status: 1,
        categoryId: 0,
        price: 0,
        stock: 0,
        subImages: [],
        detail: ''
      }
      this.TabStepActive = '0'
      this.tabDiv = true
      this.requestDiv = false
      this.successDiv = false
    },
    //
    backhome() {
      this.$router.push('/goods_list')
    }
  }
}
</script>

<style lang="less" scoped>
</style>
